#include "sprite_application.h"
#include <graphics/sprite_renderer.h>
#include <system/platform.h>
#include <assets/png_loader.h>
#include <graphics/image_data.h>
#include <graphics/texture.h>
#include <iostream>
#include "box2d_helpers.h"


SpriteApplication::SpriteApplication(abfw::Platform& platform) :
	abfw::Application(platform),
	sprite_renderer_(NULL)
{
}

SpriteApplication::~SpriteApplication()
{
}

void SpriteApplication::Init()
{
	// load the font to draw the on-screen text
	bool font_loaded = font_.Load("comic_sans", platform_);
	if(!font_loaded)
	{
		std::cout << "Font failed to load." << std::endl;
		exit(-1);
	}

	// create the Box2D physics world
	world_ = new b2World(gravity);
 
	b2Vec2 gravity(0.0f, -10.0f);


	// create a sprite renderer to draw the sprites
	sprite_renderer_ = platform_.CreateSpriteRenderer();

	// create input manager to read sony game controllers
	controller_manager_ = platform_.CreateSonyControllerInputManager();

	//
	// initialise the sprite properties
	//
	// set the width and height to be 32
	my_sprite_.set_width(32.0f);
	my_sprite_.set_height(32.0f);

	// set the sprite position to be the centre of the screen
	my_sprite_.set_position(abfw::Vector3(platform_.width()*0.5f, platform_.height()*0.5f, 0.f));
}

void SpriteApplication::CleanUp()
{
	// free up input manager
	delete controller_manager_;
	controller_manager_ = NULL;
	
	delete world_;
	world_ = NULL;

	// free up the sprite renderer
	delete sprite_renderer_;
	sprite_renderer_ = NULL;
}

bool SpriteApplication::Update(float ticks)
{
	// calculate the frame rate
	frame_rate_ = 1.0f / ticks;

	if(controller_manager_)
		controller_manager_->Update();

	return true;
}

void SpriteApplication::Render()
{
	// set up sprite renderer for drawing
	sprite_renderer_->Begin();

	//
	// draw all sprites here
	//
	sprite_renderer_->DrawSprite(my_sprite_);

	font_.RenderText(sprite_renderer_, abfw::Vector3(850.0f, 510.0f, -0.9f), 1.0f, 0xff00ffff, abfw::TJ_LEFT, "FPS: %.1f", frame_rate_);

	// tell sprite renderer that all sprites have been drawn
	sprite_renderer_->End();
}